<style lang="less">
    @import '../../../styles/common.less';
</style>

<template>
    <div>
        <Row :gutter="10">
            <Col span="6">
            <Card>
                <p slot="title">
                    <Icon type="ios-toggle"></Icon>
                        组织机构
                </p>
                <Tree ref="organizations" :data="organizations" @on-select-change="onSelectChange"></Tree>
            </Card>
            </Col>
            <Col span="18">
            <Card>
                <p slot="title">
                    <Icon type="ios-cog"></Icon>
                    组织机构明细
                </p>
                <Row :gutter="10" type="flex" justify="center" align="middle" class="switch-language-row1">
                    <Col span="24" >
                    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                        <FormItem label="机构名称" prop="name">
                            <Input v-model="formValidate.name" placeholder="输入组织机构名称"></Input>
                        </FormItem>
                        <FormItem label="机构编码" prop="code">
                            <Input v-model="formValidate.code" placeholder="输入机构编码"></Input>
                        </FormItem>
                        <FormItem label="机构负责人" prop="masterId">
                          <Select  v-model="formValidate.masterId" filterable placeholder="选择机构负责人">
                            <i-option  v-for="master in masters" :value="master.id" :key="master.id">{{master.name}}</i-option>
                          </Select>
                        </FormItem>
                        <FormItem label="显示顺序" prop="priority">
                            <Select v-model="formValidate.priority" placeholder="选择显示顺序">
                                <i-option  v-for="sort in 10" :value="sort" :key="sort">{{sort}}</i-option>
                            </Select>
                        </FormItem>
                        <FormItem label="父组织" prop="parentId">
                            <Cascader :data="records" filterable v-model="formValidate.fullParentIds" trigger="click" change-on-select></Cascader>
                        </FormItem>
                       <FormItem label="状态" prop="status">
                            <i-switch v-model="statusBoolean" size="large">
                                <span slot="NORMAL">有效</span>
                                <span slot="INVALID">失效</span>
                            </i-switch>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" @click="handlePostOrPut('formValidate')">保存</Button>
                            <Button @click="handleRest()" style="margin-left: 8px">重置</Button>
                        </FormItem>
                    </Form>
                    </Col>
                </Row>
            </Card>
            </Col>
        </Row>
    </div>
</template>

<script type="text/ecmascript-6">
import filters from '@/libs/filters'
import api from '@/libs/api'
export default {
  name: 'organization',
  data () {
    return {
      organizations: [
        {
          title: '组织机构',
          expand: true,
          children: []
        }
      ],
      records: [],
      statusBoolean: true,
      masters: [], // 负责人列表
      formValidate: {
        id: '',
        name: '',
        code: '',
        priority: '',
        masterId: '',
        parentId: '',
        status: 'NORMAL',
        fullParentIds: []
      },
      ruleValidate: {
        name: [
          { required: true, message: '机构名称不允许为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '机构编码不允许为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSelectChange (data) {
      let self = this
      data.expand = !data.expand
      if (typeof data[0] !== 'undefined') {
        self.formValidate = JSON.parse(JSON.stringify(data[0])) // 深度拷贝数据
      }
    },
    // 重置
    handleRest () {
      this.$refs['formValidate'].resetFields()
      this.formValidate.fullParentIds = []
      this.formValidate.id = ''
    },
    // 读取数据
    handleRead () {
      let self = this
      let data = {}
      this.$get(api.organizations.tree,data).then(response => {
        var records = []
          response.obj&& response.obj.forEach(function (organization) {
          // 树形tree所需数据格式
          organization.title = organization.name
          organization.expand = false
          // 级联组件所需数据格式
          organization.value = organization.id
          organization.label = organization.name
          organization.fullParentIds = filters.split(organization.fullParentIds, '/', [])
          self.handleTree(organization)
          records.push(organization)
        })
        self.organizations.children = records
        self.records = records
        self.$set(self.organizations[0], 'children', this.records)
      })
    },
    handleMaster () {
      // 初始化负责人列表
      let self = this
      self.masters = []
      self.$get(api.organizations.master,{}).then(response => {
          response.obj&& response.obj.forEach(function (user) {
          let master = {}
          master.id = user.id
          master.name = user.name
          self.masters.push(master)
        })
      })
    },
    handleTree (organization) {
      var self = this
      var childrenArray = []
      organization.childrensView.forEach(function (childrens) {
        var children = {}
        children = childrens
        // 树形tree所需数据格式
        children.title = childrens.name
        children.expand = false
        // 级联组件所需数据格式
        children.value = childrens.id
        children.label = childrens.name
        children.fullParentIds = filters.split(children.fullParentIds, '/', [])
        childrenArray.push(children)
      })
      organization.children = childrenArray
      childrenArray.forEach(function (item) {
        if (item.childrensView.length > 0) { self.handleTree(item) } else { item.children = [] }
      })
    },
    handlePostOrPut (name) {
      let self = this
      this.$refs[name].validate((valid) => {
        if (valid) {
          // 去除冗余请求数据
          delete self.formValidate['children']
          delete self.formValidate['childrensView']
          let formValidate = JSON.parse(JSON.stringify(self.formValidate))
          formValidate.parentId = formValidate.fullParentIds.length > 0 ? formValidate.fullParentIds[formValidate.fullParentIds.length - 1] : ''
          formValidate.fullParentIds = formValidate.fullParentIds.length > 0 ? filters.separatorArray(formValidate.fullParentIds, '/') : ''
          if (self.formValidate.id == '') { // 新增
            self.$post(api.organizations.base,formValidate).then(res => {
              if (res.code == 200) {
                self.handleRest()
                self.handleRead()
              }
            })
          } else { // 更新
            self.$put(api.organizations.base+"/"+self.formValidate.id,formValidate).then(res => {
              if (res.code == 200) {
                self.handleRest()
                self.handleRead()
              }
            })
          }
        }
      })
    }
  },
  created () {
    this.handleRead()
    this.handleMaster()
  },
  watch: {
    statusBoolean: function (val, oldVal) {
      this.formValidate.status = val ? 'NORMAL' : 'INVALID'
    }
  }
}
</script>

<style>

</style>
